package com.aynu.gulimall.ware.service.impl;

import com.aynu.common.constant.WareConstant;
import com.aynu.gulimall.ware.entity.PurchaseDetailEntity;
import com.aynu.gulimall.ware.service.PurchaseDetailService;
import com.aynu.gulimall.ware.service.WareSkuService;
import com.aynu.gulimall.ware.vo.MergeVo;
import com.aynu.gulimall.ware.vo.PurchaseDoneVo;
import com.aynu.gulimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aynu.common.utils.PageUtils;
import com.aynu.common.utils.Query;

import com.aynu.gulimall.ware.dao.PurchaseDao;
import com.aynu.gulimall.ware.entity.PurchaseEntity;
import com.aynu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveChase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",1).or().eq("status",0)
        );

        return new PageUtils(page);
    }

    //合并采购需求单
    @Transactional
    @Override
    public void mergePurchase(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        //1、如果没有purchaseId，则新建一个采购单（PurchaseEntity）
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATE.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单状态未0，1才可以合并
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        //如果采购单不是新建或分配状态则不能进行合并采购单
        if (!purchaseEntity.getStatus().equals(WareConstant.PurchaseEnum.CREATE.getCode())
                && !purchaseEntity.getStatus().equals(WareConstant.PurchaseEnum.ASSIGNED.getCode())){
            return;
        }

        //2、改变采购项和采购单的状态
        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);
        PurchaseEntity purchaseEntity1 = new PurchaseEntity();
        purchaseEntity1.setUpdateTime(new Date());
        this.updateById(purchaseEntity1);
    }

    /**
     * 工作人员领取采购单
     * @param purchaseIds 采购单的id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receivedPurchase(List<Long> purchaseIds) {
        //1、确认采购单是新建或者已分配状态
        List<PurchaseEntity> collect = purchaseIds.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(f -> {
            if (f.getStatus() == WareConstant.PurchaseEnum.CREATE.getCode() ||
                    f.getStatus() == WareConstant.PurchaseEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(m->{
            m.setStatus(WareConstant.PurchaseEnum.RECEIVE.getCode());
            m.setUpdateTime(new Date());
            return m;
        }).collect(Collectors.toList());

        //2、改变采购单状态
        this.updateBatchById(collect);

        //3、改变采购项状态
        collect.forEach((item)->{
            List<PurchaseDetailEntity> purchaseDetailEntities =  purchaseDetailService.listDetailByPurchaseId(item);
            List<PurchaseDetailEntity> collect1 = purchaseDetailEntities.stream().map(entites -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entites.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect1);
        });
    }

    /**
     *工作人员完成采购单
     * @param vos
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo vos) {
        //1、改变采购项状态
        boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        List<PurchaseItemVo> items = vos.getItems();
        if (items==null) {
            return ;
        }
        for (PurchaseItemVo purchaseItemVo:items){
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (purchaseItemVo.getStatus() == WareConstant.PurchaseDetailEnum.HASERROR.getCode()) {
                flag=false;
                purchaseDetailEntity.setStatus(purchaseItemVo.getStatus());
            }else{
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.FINISH.getCode());
                //2、将成功的采购商品进行入库
                PurchaseDetailEntity byId = purchaseDetailService.getById(purchaseItemVo.getItemId());
                wareSkuService.addStock(byId.getSkuId(),byId.getSkuNum(),byId.getWareId());

            }
            purchaseDetailEntity.setId(purchaseItemVo.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        //3、改变采购单的状态
        Long id = vos.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseEnum.FINISH.getCode()
                :WareConstant.PurchaseEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
    }

}